// src/store/userStore.ts

import { create } from 'zustand';
import { fetchUserProfile } from '@/services/authService';

export interface UserProfile {
  userId: string;
  firstName: string;
  lastName: string;
  email: string;
  role: string;
  permissions: number[];
}

interface UserStore {
  user: UserProfile;
  loading: boolean;
  error: string;
  setUser: (user: UserProfile | ((prev: UserProfile) => UserProfile)) => void;
  clearUser: () => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string) => void;
  initUser: () => Promise<void>;
  refreshUserPermissions: () => Promise<void>;
}

export const useUserStore = create<UserStore>((set) => ({
  user: {
    userId: '',
    firstName: '',
    lastName: '',
    email: '',
    role: '',
    permissions: [],
  },
  loading: false,
  error: '',
  setUser: (userOrFn) =>
    set((state) => ({
      user:
        typeof userOrFn === 'function'
          ? (userOrFn as (prev: UserProfile) => UserProfile)(state.user)
          : userOrFn,
    })),
  clearUser: () =>
    set({
      user: {
        userId: '',
        firstName: '',
        lastName: '',
        email: '',
        role: '',
        permissions: [],
      },
      error: '',
      loading: false,
    }),
  setLoading: (loading) => set({ loading }),
  setError: (error) => set({ error }),
  initUser: async () => {
    const token = localStorage.getItem('token');
    if (!token) return;
    set({ loading: true, error: '' });
    try {
      const data = await fetchUserProfile(token);
      set({
        user: {
          userId: '',
          firstName: data.first_name || '',
          lastName: data.last_name || '',
          email: data.email,
          role: data.role_name || '',
          permissions: data.permission_ids,
        },
        loading: false,
        error: '',
      });
    } catch (e: unknown) {
      console.error('Failed to initialize user:', e);
      // Clear token if it's invalid
      localStorage.removeItem('token');
      const errorMessage = e instanceof Error ? e.message : 'Failed to fetch user';
      set({
        user: {
          userId: '',
          firstName: '',
          lastName: '',
          email: '',
          role: '',
          permissions: [],
        },
        error: errorMessage,
        loading: false
      });
    }
  },

  refreshUserPermissions: async () => {
    const token = localStorage.getItem('token');
    if (!token) return;

    set({ loading: true, error: '' });
    try {
      const data = await fetchUserProfile(token);
      set({
        user: {
          userId: '', // UserInfoResponse doesn't include user_id
          firstName: data.first_name || '',
          lastName: data.last_name || '',
          email: data.email,
          role: data.role_name || '',
          permissions: data.permission_ids,
        },
        loading: false,
        error: '',
      });
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : 'Failed to fetch user';
      set({ error: errorMessage, loading: false });
    }
  },
}));